#include "../src/cyclelist.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* 声明底层链表的函数库 */
extern func_cyclelist fun_cyclelist;

typedef struct _tag_value // 
{
    CyclelistNode Header; // 链表逻辑节点
    int value;             // 业务节点的类型标识
} value_t;


int main(int argc, char const **argv)
{
    int Length = 0, i = 0;
    value_t  d1, d2, d3, d4, d5, d6, d7, d8;
    d1.value = 1; 
    d2.value = 2; 
    d3.value = 3; 
    d4.value = 4;
    d5.value = 5; 
    d6.value = 6; 
    d7.value = 7; 
    d8.value = 8;

    /* 创建新的链表 */
    Cyclelist *list = fun_cyclelist.create();
    /* 插入节点，尾插入法 */
    fun_cyclelist.insert(list, (CyclelistNode *)&(d1), fun_cyclelist.length(list)); // 1
    fun_cyclelist.insert(list, (CyclelistNode *)&(d2), fun_cyclelist.length(list)); // 2
    fun_cyclelist.insert(list, (CyclelistNode *)&(d3), fun_cyclelist.length(list)); // 3
    fun_cyclelist.insert(list, (CyclelistNode *)&(d4), fun_cyclelist.length(list)); // 4
    fun_cyclelist.insert(list, (CyclelistNode *)&(d5), fun_cyclelist.length(list)); // 5
    fun_cyclelist.insert(list, (CyclelistNode *)&(d6), fun_cyclelist.length(list)); // 6
    fun_cyclelist.insert(list, (CyclelistNode *)&(d7), fun_cyclelist.length(list)); // 7
    fun_cyclelist.insert(list, (CyclelistNode *)&(d8), fun_cyclelist.length(list)); // 8
    
    /* 打印当前链表的长度 */
    printf("\nlinklist length = %d,  ", fun_cyclelist.length(list));
    /* 按顺序输出当前链表中的节点 */
    for (i = 0; i < fun_cyclelist.length(list); i++)
    {
        value_t *t1 = (value_t *)fun_cyclelist.current(list);
        printf("%d  ", t1->value);
        fun_cyclelist.next(list);
    }

    putchar(10);
    putchar(10);

    /* 复位游标 */
    fun_cyclelist.reset(list);

    /* 开始进行约瑟夫的问题解决 */
    printf("Josephus's order is : ");
    while (fun_cyclelist.length(list) > 0)
    {
        value_t *temp = NULL;
        for(i = 1; i < 3; i++) fun_cyclelist.next(list);

        temp = (value_t *)fun_cyclelist.current(list);

        printf("%d  ", temp->value);
        fun_cyclelist.deleteNode(list, (CyclelistNode *)temp);
    }

    /* 清空链表 */
    fun_cyclelist.clear(list);
    /* 重新获取链表的长度 */
    Length = fun_cyclelist.length(list);
    printf("\n\nlinklist length = %d\n", Length);

    /* 销毁链表*/
    fun_cyclelist.destory(&list);

    if (list == NULL)
    {
        printf("list = NULL, free success\n");
    }
    else
    {
        printf("list = %p, free failed\n", list);
        free(list);
    }


    // getchar();
    return 0;
}
